package com.fc.converters;

import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fc.entities.Activity;
import com.fc.service.ActivityService;
import com.fc.utils.ServiceLocator;

/**
 * 
 * @author aacs
 * 
 */
@Component("activityConverter")
@ApplicationScoped
public class ActivityConverter implements Converter {
	private ActivityService service;

	public ActivityService getService() {
		if (service == null) {
			service = ServiceLocator.getBean(ActivityService.class);
		}
		return service;
	}

	@Override
	public Activity getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}

		return getService().findByName(value);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value == null || !(value instanceof Activity)) {
			return "";
		}
		Activity activity = (Activity) value;
		return String.valueOf(activity.getName());
	}
}
